#include "butterfly.h"
#include <math.h>
#include <QRandomGenerator>
const static double PI=3.1416;
ButterFly::ButterFly(QObject *parent):QObject(parent)
{
    up= true; //给标志蝴蝶翅膀位置的变量赋初值
    pix_up.load("up.png"); //调用 QPixmap load() 函数加载所用到的图片
    pix_down.load("down.png");
    startTimer(100); //启动定时器，并设置时间间隔为 100 毫秒
}

QRectF ButterFly::boundingRect() const
{
    qreal adjust = 2;
    return QRectF(-pix_up.width()/2-adjust,-pix_up.height()/2-adjust,
                  pix_up.width()+2*adjust,pix_up.height()+2*adjust);
}

void ButterFly::timerEvent(QTimerEvent *)
{
    qreal edgex = scene()->sceneRect().right()+boundingRect().width()/2;
    qreal edgetop = scene()->sceneRect().top()+boundingRect().height()/2;
    qreal edgebuttom = scene()->sceneRect().bottom()+boundingRect().height()/2;
    if(pos().x()>=edgex)
        setPos(scene()->sceneRect().left(),pos().y());
    if(pos().y()<=edgetop)
        setPos(pos().x(),scene()->sceneRect().bottom());
    if(pos().y()>=edgebuttom)
        setPos(pos().x(),scene()->sceneRect().top());
    angle+= (QRandomGenerator::global()->bounded(0,10))/20.0;
    qreal dx=fabs(sin(angle*PI)*10.0);
    qreal dy= (QRandomGenerator::global()->bounded(0,20))- 10.0;
    setPos(mapToParent(dx,dy));

}

void ButterFly::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    if(up)
    {
        painter->drawPixmap(boundingRect().topLeft(),pix_up);
        up=!up;
    }
    else
    {
        painter->drawPixmap(boundingRect().topLeft(),pix_down);
        up=!up;
    }
}
